import os

def create_project_structure():
    # 使用当前工作目录作为基础路径
    base_path = os.getcwd()
    
    # 定义要创建的文件结构及内容
    structure = {
        "src": {
            "api": {
                "index.ts": """import axios from 'axios'

const apiClient = axios.create({
  baseURL: 'http://localhost:5000/api',
  timeout: 10000,
})
export default apiClient""",
                "categories.ts": """import apiClient from './index'

export default {
  getCategories() {
    return apiClient.get('/categories')
  },
  createCategory(category: { name: string }) {
    return apiClient.post('/categories', category)
  },
  deleteCategory(id: number) {
    return apiClient.delete(`/categories/${id}`)
  }
}""",
                "websites.ts": """import apiClient from './index'

export default {
  getWebsites() {
    return apiClient.get('/websites')
  },
  getWebsitesByCategory(categoryId: number) {
    return apiClient.get(`/websites/category/${categoryId}`)
  },
  createWebsite(website: { name: string; url: string; categoryId?: number }) {
    return apiClient.post('/websites', website)
  },
  deleteWebsite(id: number) {
    return apiClient.delete(`/websites/${id}`)
  },
  fetchWebsiteInfo(url: string) {
    return apiClient.get(`/websites/fetch?url=${encodeURIComponent(url)}`)
  }
}"""
            },
            "components": {
                "CategoryForm.vue": """<template>
  <el-dialog v-model=\"dialogVisible\" title=\"编辑分类\">
    <el-form :model=\"form\" label-width=\"120px\">
      <el-form-item label=\"分类名称\">
        <el-input v-model=\"form.name\" />
      </el-form-item>
      <el-form-item>
        <el-button @click=\"dialogVisible = false\">取消</el-button>
        <el-button type=\"primary\" @click=\"submitForm\">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang=\"ts\">
import { ref, watch } from 'vue'

interface Form {
  id?: number | null
  name: string
}

const props = defineProps<{
  modelValue: boolean
  initialValues: Form
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', value: Form): void
}>()

const dialogVisible = ref(props.modelValue)
const form = ref<Form>({ ...props.initialValues })

const submitForm = () => {
  emit('submit', form.value)
  dialogVisible.value = false
}

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    form.value = { ...props.initialValues }
  }
})
</script>""",
                "WebsiteForm.vue": """<template>
  <el-dialog v-model=\"dialogVisible\" title=\"编辑网址\">
    <el-form :model=\"form\" label-width=\"120px\">
      <el-form-item label=\"网址名称\">
        <el-input v-model=\"form.name\" />
      </el-form-item>
      <el-form-item label=\"URL地址\">
        <el-input v-model=\"form.url\" />
      </el-form-item>
      <el-form-item label=\"所属分类\">
        <el-select v-model=\"form.categoryId\" placeholder=\"请选择分类\">
          <el-option
            v-for=\"category in categories\"
            :key=\"category.id\"
            :label=\"category.name\"
            :value=\"category.id\"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click=\"dialogVisible = false\">取消</el-button>
        <el-button type=\"primary\" @click=\"submitForm\">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang=\"ts\">
import { ref, watch } from 'vue'
import categoriesApi from '@/api/categories'

interface Form {
  id?: number | null
  name: string
  url: string
  categoryId?: number | null
}

const props = defineProps<{
  modelValue: boolean
  initialValues: Form
  categories: Array<{ id: number; name: string }>
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', value: Form): void
}>()

const dialogVisible = ref(props.modelValue)
const form = ref<Form>({ ...props.initialValues })

const submitForm = () => {
  emit('submit', form.value)
  dialogVisible.value = false
}

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    form.value = { ...props.initialValues }
  }
})
</script>"""
            },
            "views": {
                "Home.vue": """<template>
  <el-container style="min-height: 100vh;">
    <el-header style="background-color: #409EFF; color: white;">
      <h1 style="margin: 0; line-height: 60px;">导航网站后台管理系统</h1>
    </el-header>
    <el-container>
      <el-aside width="200px" style="background-color: #f5f7fa;">
        <el-menu
          default-active="$route.path"
          router
          style="border-right: none;"
        >
          <el-menu-item index="/categories">
            <el-icon><document /></el-icon>
            <span>分类管理</span>
          </el-menu-item>
          <el-menu-item index="/websites">
            <el-icon><link /></el-icon>
            <span>网址管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <router-view />
      </el-main>
    </el-container>
    <el-footer style="text-align: center; background-color: #f5f7fa;">
      © 2025 导航网站版权所有
    </el-footer>
  </el-container>
</template>

<script setup lang=\"ts\">
import { Document as DocumentIcon, Link as LinkIcon } from '@element-plus/icons-vue'
</script>""",
                "Categories.vue": """<template>
  <div>
    <el-page-header title="返回" content="分类管理" @back=\"$router.go(-1)\" />

    <el-row style=\"margin-top: 20px;\">
      <el-col :span=\"8\">
        <el-button type=\"primary\" @click=\"showAddCategoryDialog\">添加分类</el-button>
      </el-col>
    </el-row>

    <el-table :data=\"categories\" style=\"width: 100%; margin-top: 20px;\">
      <el-table-column prop=\"id\" label=\"ID\" width=\"100\" />
      <el-table-column prop=\"name\" label=\"分类名称\" />
      <el-table-column label=\"操作\">
        <template #default=\"{ row }\">
          <el-button size=\"small\" @click=\"showEditCategoryDialog(row)\">编辑</el-button>
          <el-button size=\"small\" type=\"danger\" @click=\"deleteCategory(row.id)\">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <CategoryForm
      v-model=\"showCategoryDialog\"
      :initial-values=\"currentCategory\"
      @submit=\"handleCategorySubmit\"
    />
  </div>
</template>

<script setup lang=\"ts\">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import categoriesApi from '@/api/categories'
import CategoryForm from '@/components/CategoryForm.vue'

interface Category {
  id?: number;
  name: string;
}

const categories = ref<Category[]>([])
const showCategoryDialog = ref(false)
const currentCategory = ref<Category>({ name: '' })

const loadCategories = async () => {
  try {
    const response = await categoriesApi.getCategories()
    categories.value = response.data
  } catch (error) {
    ElMessage.error('加载分类失败')
  }
}

const showAddCategoryDialog = () => {
  currentCategory.value = { name: '' }
  showCategoryDialog.value = true
}

const showEditCategoryDialog = (category: Category) => {
  currentCategory.value = { ...category }
  showCategoryDialog.value = true
}

const handleCategorySubmit = async (formData: Category) => {
  try {
    if (formData.id) {
      // 编辑分类
      await categoriesApi.updateCategory(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 添加分类
      await categoriesApi.createCategory(formData)
      ElMessage.success('创建成功')
    }
    await loadCategories()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteCategory = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个分类吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await categoriesApi.deleteCategory(id)
    ElMessage.success('删除成功')
    await loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadCategories()
})
</script>""",
                "Websites.vue": """<template>
  <div>
    <el-page-header title="返回" content="网址管理" @back=\"$router.go(-1)\" />

    <el-row style=\"margin-top: 20px;\">
      <el-col :span=\"8\">
        <el-button type=\"primary\" @click=\"showAddWebsiteDialog\">添加网址</el-button>
      </el-col>
    </el-row>

    <el-table :data=\"websites\" style=\"width: 100%; margin-top: 20px;\">
      <el-table-column prop=\"id\" label=\"ID\" width=\"100\" />
      <el-table-column prop=\"name\" label=\"网址名称\" />
      <el-table-column prop=\"url\" label=\"URL地址\" />
      <el-table-column prop=\"categoryName\" label=\"所属分类\" />
      <el-table-column label=\"操作\">
        <template #default=\"{ row }\">
          <el-button size=\"small\" @click=\"showEditWebsiteDialog(row)\">编辑</el-button>
          <el-button size=\"small\" type=\"danger\" @click=\"deleteWebsite(row.id)\">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <WebsiteForm
      v-model=\"showWebsiteDialog\"
      :initial-values=\"currentWebsite\"
      :categories=\"categories\"
      @submit=\"handleWebsiteSubmit\"
    />
  </div>
</template>

<script setup lang=\"ts\">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import websitesApi from '@/api/websites'
import categoriesApi from '@/api/categories'
import WebsiteForm from '@/components/WebsiteForm.vue'

interface Website {
  id?: number;
  name: string;
  url: string;
  categoryId?: number | null;
  categoryName?: string;
}

interface Category {
  id: number;
  name: string;
}

const websites = ref<Website[]>([])
const categories = ref<Category[]>([])
const showWebsiteDialog = ref(false)
const currentWebsite = ref<Website>({ name: '', url: '' })

const loadWebsites = async () => {
  try {
    const response = await websitesApi.getWebsites()
    websites.value = response.data.map((website: any) => ({
      ...website,
      categoryName: website.category?.name || ''
    }))
  } catch (error) {
    ElMessage.error('加载网址失败')
  }
}

const loadCategories = async () => {
  try {
    const response = await categoriesApi.getCategories()
    categories.value = response.data
  } catch (error) {
    ElMessage.error('加载分类失败')
  }
}

const showAddWebsiteDialog = () => {
  currentWebsite.value = { name: '', url: '', categoryId: null }
  showWebsiteDialog.value = true
}

const showEditWebsiteDialog = (website: Website) => {
  currentWebsite.value = { ...website }
  showWebsiteDialog.value = true
}

const handleWebsiteSubmit = async (formData: Website) => {
  try {
    if (formData.id) {
      // 编辑网址
      await websitesApi.updateWebsite(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 添加网址
      await websitesApi.createWebsite(formData)
      ElMessage.success('创建成功')
    }
    await Promise.all([loadWebsites(), loadCategories()])
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteWebsite = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个网址吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await websitesApi.deleteWebsite(id)
    ElMessage.success('删除成功')
    await loadWebsites()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(async () => {
  await Promise.all([loadWebsites(), loadCategories()])
})
</script>"""
            },
            "router": {
                "routes.ts": """import type { RouteRecordRaw } from 'vue-router'
import HomeView from '@/views/Home.vue'
import CategoriesView from '@/views/Categories.vue'
import WebsitesView from '@/views/Websites.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: HomeView,
    redirect: '/categories',
    children: [
      {
        path: '/categories',
        name: 'Categories',
        component: CategoriesView
      },
      {
        path: '/websites',
        name: 'Websites',
        component: WebsitesView
      }
    ]
  }
]

export default routes""",
                "index.ts": """import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router"""
            },
            "App.vue": """<template>
  <router-view />
</template>

<script setup lang=\"ts\">
// 这里可以添加全局逻辑
</script>

<style scoped>
/* 全局样式可以在main.css中定义 */
</style>"""
        }
    }

    def create_structure(current_path, structure_dict):
        for name, content in structure_dict.items():
            current_item_path = os.path.join(current_path, name)

            # 如果内容是字典，说明是文件夹
            if isinstance(content, dict):
                os.makedirs(current_item_path, exist_ok=True)
                create_structure(current_item_path, content)
            else:
                # 如果是字符串，说明是文件
                os.makedirs(os.path.dirname(current_item_path), exist_ok=True)
                
                # 仅当文件不存在时才写入内容
                if not os.path.exists(current_item_path):
                    with open(current_item_path, 'w', encoding='utf-8') as f:
                        f.write(content)
                    print(f"创建文件: {current_item_path}")
                else:
                    print(f"跳过已存在的文件: {current_item_path}")

    create_structure(base_path, structure)


if __name__ == "__main__":
    print("开始创建项目结构（基于当前目录）...")
    create_project_structure()
    print("\n项目结构已创建或检查完成（位于当前目录）。")